package com.hzit.servlet;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.hzit.entity.Student;
import com.hzit.mapper.StudentMapper;
import com.hzit.service.StudentService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@WebServlet("/student")
public class StudentServlet extends HttpServlet {
	private StudentMapper studentMapper;

	@Override
	public void init() throws ServletException {
		 //1. 在servlet容器中得到spring容器
		 WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
		 //2. 从spring容器中得到javabean对象
		 studentMapper = wac.getBean(StudentMapper.class);

	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1. 处理post请求的中文乱码
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=utf-8");
		//2. 得到请求参数
		String cmd = req.getParameter("cmd");
		//3. 根据参数调用方法
		if(StrUtil.isNotBlank(cmd)){
			if("list".equals(cmd)){
				list(req,resp);
			}
		}
	}
	//2. 列表学生
	private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//2.1 查询所有学生
		 List<Student> students = studentMapper.selectByExample(null);
		//2.2 输出到页面
		String s = JSON.toJSONString(students);
		resp.getWriter().println(s);
		resp.getWriter().flush();
	}
}
